<?php
/**
-------------------------
GNU GPL COPYRIGHT NOTICES
-------------------------
This file is part of FlexicaCMS.

FlexicaCMS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

FlexicaCMS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with FlexicaCMS.  If not, see <http://www.gnu.org/licenses/>.*/

/**
 * $Id$
 *
 * @author FlexicaCMS team <contact@flexicacms.com>
 * @link http://www.flexicacms.com/
 * @copyright Copyright &copy; 2009-2010 Gia Han Online Solutions Ltd.
 * @license http://www.flexicacms.com/license.html
 */

class UserController extends BackOfficeController{

    public function actionList(){
        $model = new FUser('search');
        if(isset($_GET['FUser']))
            $model->attributes=$_GET['FUser'];

        $this->render('List', array('model' => $model));
    }

    /**
    * Create a new user
    * This equal to calling edit action with User ID = 0
    */
    public function actionNew(){
        $this->actionEdit();
    }

    /**
    * Edit user
    * User query string Id parameter as the User ID, if Id=0 or not provided
    * the action will create a new user
    */
	public function actionEdit()
	{
		$userId = $this->get('Id',0);
		if ($userId == 0) {
            $user = new FUser();
            $user->Status = FUser::STATUS_MEMBER;
        } else {
            $user = FUser::model()->findByPk($userId);
		}

        if (!is_null($user)){
        	$user->Password = ''; // We don't  show user password
        }else{
            ErrorHandler::logError(Yii::t('User', 'Invalid user Id.'));
        }

        $this->render('Edit',array('user' => $user));
	}

    public function actionForgotPassword()
    {
        $result = false;
        $user = new FUser();

        if (Yii::app()->request->isPostRequest)
        {
            $result = FSM::run('User/Account/forgotPassword', $_POST);
            if ($result->ReturnCode !== ServiceResult::RETURN_SUCCESS)
            {
                ErrorHandler::logErrors($result->ErrorMessages);
                $user = $result->ReturnedData['User'];
            }
        }

        Yii::app()->layout = '';
        $this->render('SendAuthenticationEmail', array('user' => $user,
	                                            'result' => $result,
	                                            'action' => 'forgotPassword'));
    }
        
    public function actionSendActivation()
    {
		$result = false;
        $user = new FUser();

        if (Yii::app()->request->isPostRequest)
        {
            $result = FSM::run('User/Account/sendActivation', $_POST);
            if ($result->ReturnCode !== ServiceResult::RETURN_SUCCESS)
            {
                ErrorHandler::logErrors($result->ErrorMessages);
                $user = $result->ReturnedData['User'];
            }
        }       

        Yii::app()->layout = '';
        $this->render('SendAuthenticationEmail', array('user' => $user,
		                                            'result' => $result,
		                                            'action' => 'sendActivation'));	
    }

    public function actionUpdateAccount()
    {
        $user = FUser::model()->findByPk(Yii::app()->user->Id);
        if (Yii::app()->request->isPostRequest)
        {
            $result = FSM::run('Core.Account.edit', $_POST);
            if ($result->hasErrors())
            {
                $this->error = $result->getErrors();
                //FErrorHandler::logErrors($result->ErrorMessages);
            }
            else
            {
                $this->message = Yii::t('User', 'USER_ACCOUNT_UPDATED_SUCCESSFULLY');
            }
            $this->redirect(array('/Core/user/updateAccount'));
        }
        $this->render('EditAccount', array('user' => $user));
    }

	public function actionSave(){
        //Make sure this action can be requested only by POST
		if (Yii::app()->request->IsPostRequest){
            $url = $this->createUrl('/Core/user/edit', array('Id' => $this->post('FUser[Id]')));

			$userId = $this->post('FUser[Id]',0);
			if ($userId == 0){
                //Create a new user
                $result = FSM::run('Core.Account.register', $_POST);
                if (! $result->hasErrors())
                    $this->message = Yii::t('User', 'User created successfully.');
                    
			} else {
                //Update user
                $result = FSM::run('Core.Account.update', $_POST);
                if (! $result->hasErrors())
                    $this->message = Yii::t('User', 'User updated successfully.');
            }

            $this->redirect($url);
		}
        else
            $this->redirect($this->createUrl('/Core/user'));
	}

    /**
    * Login in BackOffice
    */
    public function actionLogin(){
        $user = new FUser();
        $invalidStatusCase = false;
        if (Yii::app()->request->IsPostRequest) {
            $result = FSM::run('Core.Account.login', $_POST);
            if ($result->hasErrors()){
//                $error = $result->ErrorMessages;
                echo $result->error;
                if ($result->error == FUserIdentity::ERROR_STATUS_INVALID)
                {
					$invalidStatusCase = true;
                }
            } else {
                if (($url = Yii::app()->user->returnUrl) != '')
                    Yii::app()->controller->redirect($url);
                else
                    $this->redirect(Yii::app()->request->getBaseUrl(true));            
            }
        }
        if (Yii::app()->user->isGuest === false) {
            $this->redirect(Yii::app()->request->getBaseUrl(true));
        }
        Yii::app()->layout = 'login';
        $this->render('Login', array('user' => $user));
    }

    /**
    * Logout user and redirect to homepage
    */
    public function actionLogout(){
        FSM::run('User/Account/logout', array());
        $this->redirect(Yii::app()->request->getBaseUrl(true));
    }

    public function actionBulk()
    {
        if(Yii::app()->request->isPostRequest)
        {
            $action = '';
            $ids = array();
            if (isset($_GET['Id']) && isset($_GET['action'])) {
                $ids[] = $_GET['Id'];
                $action = $_GET['action'];
            } elseif (isset($_POST['Id']) && isset($_POST['action'])) {
                $ids = $_POST['Id'];
                $action = $_POST['action'];
            }
            if (is_array($ids) && count($ids)) {
                switch($action)
                {
                    case 'delete':
                        $result = FSM::run('Core.Account.deleteUsers', array('ids' => $ids));
                        if ($result->hasErrors()) //ServiceResult::ERR_UNAUTHORIZED
                        {
                            throw new CHttpException(403);
                        }
                        break;
                    default:
                        throw new CHttpException(404,'The requested page does not exist.');
                }
            }
            else
                throw new CHttpException(404,'The requested page does not exist.');
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }
    
    public function actionViewProfile()
    {
		$userId = $this->get('UserId', 0);
		$user = new FUser();
		if ($userId > 0)
		{
			$user = FUser::model()->findByPk($userId);
		}
		
		$this->render('ViewProfile', array('user' => $user));	
    }
    
    public function actionResendActivation()
    {
		$userId = $this->get('Id', 0);
		$user = null;
		if ($userId > 0)
		{
			$user = FUser::model()->findByPk($userId);
			if (!is_null($user))
			{                    
				$result = FSM::run('User/Account/resendActivation', array('user' => $user, 'rawPassword' => null));
			}
		}
		$this->render('ResendActivation', array('result' => $result));
    }
}